package org.b3log.symphony.TimeJob;

import java.io.UnsupportedEncodingException;
import java.util.Iterator;

import org.b3log.symphony.model.BackDoor;
import org.b3log.symphony.util.HtmlUtil;
import org.quartz.JobExecutionException;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import jodd.http.HttpRequest;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 类TimeJob的实现描述：TODO
 *
 * @author Gai 2019/10/19 18:26
 */
@Slf4j
public class JiShuApi {
    public final String NEWS_URL_FROM_JISHU = "https://api.jisuapi.com/news/get?appkey=501379c43b807665";

    //
    public static void main(String[] args) throws JobExecutionException, UnsupportedEncodingException {
        JiShuApi jiShuApi = new JiShuApi();
        JSONObject newsResult = jiShuApi.getNewS("头条", 0, 1);
        log.info(newsResult.toString());
        if (0 != newsResult.getIntValue("status") || !"ok".equals(newsResult.getString("msg"))) {
            log.error("the news getting whiling error");
            return;
        }

        JSONObject map = buildArticle(newsResult.getJSONObject("result").getJSONArray("list"));
        HttpRequest.post("http://localhost:8080/symphony/article").body(JSONObject.toJSONString(map)).send();
    }

    private static JSONObject buildArticle(JSONArray jsonArray) {
        Iterator<Object> iterator = jsonArray.iterator();
        JSONObject hashMap = new JSONObject();
        while (iterator.hasNext()) {
            JSONObject jsonObject = ((JSONObject) iterator.next());
            hashMap.put("articleTitle", jsonObject.getString("title"));
            hashMap.put("articleContent", HtmlUtil.removeHtmlTag(jsonObject.getString("content")));
            hashMap.put("articleTags", "热点头条");
            hashMap.put("articleAuthorId", "admin");
            hashMap.put("articleCommentable", true);
            hashMap.put("articleNotifyFollowers", false);
            hashMap.put("articleType", 0);
            hashMap.put("articleShowInList", 1);
            hashMap.put("articleRewardContent", "");
            hashMap.put("articleRewardPoint", "");
            hashMap.put("key", BackDoor.BACK_DOOR_Key);
        }

        return hashMap;
    }

    //channel=头条&start=0&num=10&appkey=501379c43b80766
    JSONObject getNewS(String channel, int start, int num) {
        StringBuilder sb = new StringBuilder(NEWS_URL_FROM_JISHU);
        if (StringUtil.isNotBlank(channel))
            sb.append("&channel=").append(channel);
        sb.append("&num=").append(num);
        sb.append("&start=").append(start);

        log.info("get news by post url = {}", sb);
        return JSONObject.parseObject(HttpRequest.post(sb.toString()).send().body());

    }

    public void execute() throws JobExecutionException, UnsupportedEncodingException {

    }
}
